﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;
using System.Xml.Serialization;

namespace WebLib.AuthorizeService
{
    public class Authentication
    {
        private readonly Identity _identity;
        private readonly UserDataModel _userDataModel;

        public Authentication(UserDataModel userDataModel)
        {
            _identity = new Identity(userDataModel.UserId, userDataModel.UserName, userDataModel.UserRoles);
            _userDataModel = userDataModel;
        }

        public void SetTicket()
        {
            var expireTime = DateTime.MinValue;

            var xs = new XmlSerializer(typeof(UserDataModel));
            var sw = new StringWriter();
            xs.Serialize(sw, _userDataModel);

            if (FormsAuthentication.Timeout.TotalMinutes > 0)
                expireTime = DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes);

            var ticket = new FormsAuthenticationTicket(
                1,
                _identity.UserId,
                DateTime.Now,
                expireTime,
                false,
                sw.ToString(),
                FormsAuthentication.FormsCookiePath);


            var hash = FormsAuthentication.Encrypt(ticket);
            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash)
            {
                Domain = FormsAuthentication.CookieDomain
            };

            HttpContext.Current.Response.Cookies.Add(cookie);
        }
    }
}
